package com.qf.controller;

import com.alibaba.fastjson.JSON;
import com.qf.dto.UserDto;
import com.qf.pojo.User;
import com.qf.service.Impl.UserServiceImpl;
import com.qf.service.UserService;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;


@WebServlet("/userLoginController.action")
public class UserLoginController extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //登录，获取前端数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //封装对象
        UserDto userDto = new UserDto();
        userDto.setUsername(username);
        userDto.setPassword(password);

        //调用业务层方法
        User user = userService.login(userDto);

        //创建集合
        HashMap<String, Object> map = new HashMap<>();

        //判断
        if(user != null){
            //表示登录成功
            //我们把用户信息存储到Session中，
            // req.getSession(boolean create)：true或者不写，表示没有HttpSession对象就创建一个，有就直接返回
            // req.getSession(boolean create)：false表示获取HttpSession对象，有就返回，没有返回null
            HttpSession session = req.getSession();
            session.setAttribute("user",user);

            map.put("state",200);
            map.put("data",user);
            map.put("massage","success");

            resp.getWriter().write(JSON.toJSONString(map));
        }else{
            map.put("state",-1);
            map.put("massage","fail");
            resp.getWriter().write(JSON.toJSONString(map));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
